(function (w) {
    //ajax请求地址
    w.urlRoot = 'https://sakihomura.top:7002/';
    w.pattern_forRoot = /[A-Za-z0-9:]+\/\/[A-Za-z0-9:.]+\//;
    let cover = document.querySelector('.cover');

    hideCover = function () {// hideCover :隐藏遮盖层
        cover.style.display = 'none';
    }
    showCover = function () {// showCover : 展示遮盖层
        cover.style.display = 'block';
    }

    w.showBar = function (bar) {// showBar ： 展示模态框
        bar.style.display = 'block';
        stopScroll();
        showCover();
    }
    w.closeBar = function (bar) {// closeBar ： 关闭模态框
        bar.style.display = 'none';
        resumeScroll();
        hideCover();
    }


    let moveEvent = function (e) { e.preventDefault(); }
    // 阻止屏幕滚动(PC端)
    let stopScroll = function () {
        window.addEventListener('wheel', moveEvent, { passive: false });
    }
    // 取消滚动限制(PC端)
    let resumeScroll = function () {
        window.removeEventListener('wheel', moveEvent, { passive: false });
    }
    /*
    // 阻止屏幕滚动(移动端)
    function stop(){
        document.body.style.overflow='hidden';        
        document.addEventListener("touchmove",moveEvent,false);
    }
    // 取消滑动限制(移动端)
    function move(){
        document.body.style.overflow='';//出现滚动条
        document.removeEventListener("touchmove",moveEvent,false);        
    }
    */


    let close_bar_btns = document.querySelectorAll('.close_bar_btn');
    close_bar_btns.forEach(btn => { //  关闭模态框
        btn.addEventListener('click', function () {
            closeBar(this.parentNode);
        });
    });

    // 设置select中text="paraText"的第一个Item为选中        
    w.selectByValue = function (select, value) {
        for (let i = 0; i < select.options.length; i++) {
            let opt = select.options[i];
            if (opt.value == value) {
                opt.selected = true;
                return;
            }
        }
    }
    /**
     * 
     * @param {method,url,data,header} options 
        ajax({
            method: 'GET',
            url: '',
            data: {},//data为传入的json数据
            header: {//post/put/delete 修改为 application/json
                'Content-type': 'application/x-www-form-urlencoded'
            },
        }).then((json) => {
            console.log(json);
            closeBar('这里输入要关闭的窗口');
        }, (error) => {
            alert(error);
            closeBar('这里输入要关闭的窗口');
        });
     */
    w.ajax = function (options) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            //默认参数
            let def = {
                method: 'GET',
                url: '',
                data: {},
                header: {
                    'Content-type': 'application/x-www-form-urlencoded',
                },
            }
            Object.assign(def, options);
            def.method = def.method.toUpperCase();//转化为全大写
            //拼接参数
            let params = '';
            if (!util.isEmptyObject(def.data)) {//data不为空
                for (const key in def.data) {
                    if (Object.hasOwnProperty.call(def.data, key)) {
                        params += `${key}=${def.data[key]}&`;
                    }
                }
                //去掉最后一个 &
                params = params.substr(0, params.length - 1);
                if (def.method === 'GET') {//get方式在url后添加参数
                    def.url += `?${params}`;
                }
            }
            xhr.open(def.method, def.url);
            if (def.method === 'POST' || def.method === 'DELETE' || def.method === 'PUT') {
                if (def.header['Content-type'] === 'application/json') {
                    xhr.setRequestHeader('Content-type', 'application/json');
                    xhr.send(JSON.stringify(def.data));
                } else {
                    xhr.send(params);
                }
            } else if (def.method === 'GET') {
                xhr.send();
            }

            xhr.onreadystatechange = function () {
                // console.log('xhr.status = ' + xhr.status);
                if (util.isReceived(xhr)) {
                    // 如果是Json格式，需要把String转化为JSON对象
                    let resText = xhr.getResponseHeader('Content-type').includes('application/json') ?
                        JSON.parse(xhr.responseText) : xhr.responseText;
                    // console.log('接收到有个傻子发来的响应：',resText);
                    if (resText.meta.status < 300) {
                        resolve(resText);//成功：返回json数据
                    } else {
                        reject(resText.meta.msg);//失败：返回msg信息
                    }
                }
            }
        });
    }
})(window);